$(function() {

    //主流程对象
    var mainCtrl = avalon.define({
        $id: "mainController",
        pageType: 2,
        taskId: "",
        taskTyedis: false,
        viewdis: false,
        starttime: "",
        endtime: "",
        storageVal: "0007",
        taskType: "1",
        allCategoryBrand: [], //所有品类的品牌
        allCategory: [], //所有品类
        allBrandByCate: [], //某个品类对应的品牌
        curCategory: "", //当前选中的品类
        selBrandList: [], //当前选中了的品牌
        isSelAllCategory: false, //是否选中了所有品类品牌
        isSelAllBrand: false, //是否选中了所有品牌
        hasTree: false, //是否获取过树
        storeList: [], //被选中的树中的门店
        brandSearchName: "", //品牌的查询名称
        selCluster: function(){
            mainCtrl.storageVal = "0007";
        },
        storePop: function() {
            var stype = popCtrl.storeType;
            //如果是门店，并且门店树 么有值就去取值
            if(stype == 1 && !popCtrl.storeData) {
                getAllStore(1);
            }
            //如果是服务站，并且服务站树 么有值就去取值
            if(stype == 0 && !popCtrl.serviceData) {
                getAllStore(0);
            }
            $("#popup_cnt").show();
        },
        //点击品类，获取品牌
        getBrand: function(category) {
            mainCtrl.curCategory = category; //每次点击一次记录一次当前选中品类
            $(this).addClass("sel").siblings("li").removeClass("sel");
            var ccode = category.categoryCode;
            getBrandByCode(ccode);
            //如果是查看，不需要效果
            if(mainCtrl.pageType != 0) {
                checkSelBrand();
                //点击品类的时候，如果品牌有选中的，则在品类上要显示（已选）
                for(var i = 0; i < mainCtrl.allBrandByCate.length; i++) {
                    //如果存在选中的
                    if(mainCtrl.allBrandByCate[i].isSel) {
                        $(this).find("span").show();
                        break;
                    }
                }
            }
        },
        //品牌查询
        brandSearch: function() {
            var curCC = mainCtrl.curCategory.categoryCode; //当前品类编码
            var sName = $('#brandSearchName').val();
            getBrandByCode(curCC);
            if(sName != "") {
                var searchBrandList = [],
                    curBandList = mainCtrl.allBrandByCate,
                    curBandListLen = curBandList.length;
                for(var i = 0; i < curBandListLen; i++) {
                    var bName = curBandList[i].brandName;
                    if(bName.toLocaleUpperCase().indexOf(sName.toLocaleUpperCase()) != -1) {
                        searchBrandList.push(curBandList[i]);
                    }
                }
                mainCtrl.allBrandByCate = searchBrandList;
            }
            checkSelBrand();
        },
        //品牌选中、取消
        addbrandSelList: function(brand) {
            //如果是查看，是不允许操作的
            if(mainCtrl.pageType == 0) {
                return;
            }
            $(this).toggleClass("sel");
            //如果选中了一个品牌，就加到选中品牌列表中selBrandList
            if($(this).hasClass("sel")) {
                //选中的品牌id和品牌对应的品类id，都存下来，保存的时候需要
                var selCategoryCode = mainCtrl.curCategory.categoryCode,
                    selBrandCode = brand.brandCode,
                    selBrandObj = {
                        "categoryCode": selCategoryCode,
                        "brandCode": brand.brandCode
                    };
                mainCtrl.selBrandList.push(selBrandObj);
            } else {
                //如果取消选择，则将品牌从保存列表中删除
                var selBrands = mainCtrl.selBrandList,
                    selBrandsLen = selBrands.length,
                    curbrandCode = brand.brandCode,
                    delIdx = -1;
                for(var i = 0; i < selBrandsLen; i++) {
                    var selbcode = selBrands[i].brandCode;
                    if(curbrandCode == selbcode) {
                        delIdx = i;
                        break;
                    }
                }
                //删除该位置的值
                mainCtrl.selBrandList.splice(delIdx, 1);
                $("#allbrand").removeAttr("checked");
                mainCtrl.isSelAllBrand = false;
            }
            //如果当前选中的品牌数量大于0 则左侧当前品类显示（已选）
            var selBrandLen = $(this).parent("ul").find("li.sel").length;
            if(selBrandLen > 0) {
                $(".category-brand .category .active.sel").find("span").show();
                var allLi = $(this).parent("ul").find("li").length;
                //如果选中的长度==所有li的长度，则是当前选中了所有品牌
                if(selBrandLen == allLi) {
                    $("#allbrand").prop("checked", true);
                    mainCtrl.isSelAllBrand = true;
                }
            } else {
                $(".category-brand .category .active.sel").find("span").hide();
            }
        },
        saveTask: function() {
            $(this).next(".err-box").hide();
            if(mainCtrl.storeList.length == 0){
                $(this).next(".err-box").text("至少下发一个门店").show();
                return;
            }
            mainCtrl.starttime = $("#starttime").val();
            mainCtrl.endtime = $("#endtime").val();
            if(mainCtrl.starttime == "" || mainCtrl.endtime == ""){
                $(this).next(".err-box").text("任务开始时间结束时间不能为空").show();
                return;
            }
            if(mainCtrl.selBrandList.length == 0) {
                $(this).next(".err-box").text("至少选择一个品牌").show();
                return;
            }
            
            var brandList = mainCtrl.selBrandList.$model,
                storeList = mainCtrl.storeList.$model,
                dataJson = JSON.stringify({
                    "brandList": brandList,
                    "endTime": mainCtrl.endtime,
                    "startTime": mainCtrl.starttime,
                    "storage": mainCtrl.storageVal,
                    "taskType": mainCtrl.taskType,
                    "storeList": storeList,
                    "taskId": mainCtrl.pageType == 1 ? mainCtrl.taskId : ""
                });
            $(".loadData").show();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: dataJson,
                url: DI.saveModelTask,
                success: function(data) {
                    $(".loadData").hide();
                    if(data.retFlag == 1) {
                        window.location = "taskManage.html";
                    } else {
                        PLATFORM.showTips("error", data.errorMessage)
                    }
                }
            });
        },
        returnManage: function() {
            window.location = "taskManage.html";
        },
        //选中所有的品类品牌
        selAllCategory: function() {
            mainCtrl.selBrandList = [];
            if(!mainCtrl.isSelAllCategory) {
                mainCtrl.isSelAllCategory = true;
                mainCtrl.isSelAllBrand = true;
                var allCategory = mainCtrl.allCategory,
                    allCategoryLen = allCategory.length;
                for(var i = 0; i < allCategoryLen; i++) {
                    var selCategoryCode = allCategory[i].categoryCode;
                    var brands = allCategory[i].brandList;
                    for(var j = 0; j < brands.length; j++) {
                        var brandCode = brands[j].brandCode;
                        brandObj = {
                            "categoryCode": selCategoryCode,
                            "brandCode": brandCode
                        };
                        mainCtrl.selBrandList.push(brandObj);
                    }
                }
                //点击全选品类品牌，1要让所有的品牌为选中状态；2所有的品类显示（已选）；3全选品牌框选中
                var selList = [];
                for(var k = 0; k < mainCtrl.allBrandByCate.length; k++) {
                    mainCtrl.allBrandByCate[k].isSel = true;
                    selList.push(mainCtrl.allBrandByCate[k])
                }
                mainCtrl.allBrandByCate = selList; //所有的品牌
                $("#allcategory").prop("checked", true);
                $("#allbrand").prop("checked", true); //全选品牌选中
                $(".category-brand .category li span").show(); //所有的品类

            } else {
                mainCtrl.isSelAllCategory = false;
                mainCtrl.isSelAllBrand = false;
                var selList = [];
                for(var k = 0; k < mainCtrl.allBrandByCate.length; k++) {
                    mainCtrl.allBrandByCate[k].isSel = false;
                    selList.push(mainCtrl.allBrandByCate[k])
                }
                mainCtrl.allBrandByCate = selList;
                $("#allcategory").removeAttr("checked");
                $("#allbrand").removeAttr("checked");
                $(".category-brand .category li span").hide();
            }

        },
        selAllBrand: function() {
            //取消全选，1“全品类品牌”取消 2、品类隐藏（已选）3从品牌选中列表中删掉
            if(mainCtrl.isSelAllBrand) {
                mainCtrl.isSelAllBrand = false;
                mainCtrl.isSelAllCategory = false;
                $("#allbrand").removeAttr("checked");
                $(".category-brand .brand li").removeClass("sel");
                $(".cell.long input[type=checkbox]").removeAttr("checked");
                $(".category-brand .category li.sel span").hide();

                var saveSelBrandList = mainCtrl.selBrandList,
                    curBrands = mainCtrl.allBrandByCate,
                    curBrandsLen = curBrands.length,
                    tempSelBrandList = saveSelBrandList;
                for(var j = 0; j < tempSelBrandList.length;) {
                    var selbcode = saveSelBrandList[j].brandCode;
                    var isExist = false;
                    for(var i = 0; i < curBrandsLen; i++) {
                        var cbcode = curBrands[i].brandCode;
                        if(cbcode == selbcode) {
                            isExist = true;
                            break;
                        }
                    }
                    if(isExist) {
                        //调用splice方法后，数组长度发生了变化
                        tempSelBrandList.splice(j, 1);
                        j++;
                        j = 0;
                    } else {
                        j++;
                    }
                }
                mainCtrl.selBrandList = tempSelBrandList;
            } else {
                mainCtrl.isSelAllBrand = true;
                //看上去是全选的效果   
                $("#allbrand").prop("checked", true);
                $(".category-brand .brand li").addClass("sel");
                $(".category-brand .category li.sel span").show();
                //真正保存下来的品牌数据
                pushSelBrand();
            }
            //检查全选品牌后，所有的品牌是否都选中
            chkSelAllCategory();

        },
        getNodes: function(data) {
            for(var i = 0; i < data.length; i++) {
                if(data[i].level == "3") {
                    data[i].text = data[i].id + " " + data[i].text;
                }
            }
            return data;
        }
    });

    var pushSelBrand = function() {
        var saveSelBrandList = mainCtrl.selBrandList,
            saveSelBrandListLen = saveSelBrandList.length,
            curCategoryCode = mainCtrl.curCategory.categoryCode;
        curBrands = mainCtrl.allBrandByCate,
            curBrandsLen = curBrands.length,
            tempSelBrandList = saveSelBrandList;
        for(var k = 0; k < curBrandsLen; k++) {
            var curbrandcode = curBrands[k].brandCode;
            var isExist = false; //在原先的保存列表中是否存在
            for(var j = 0; j < saveSelBrandListLen; j++) {
                var savebrandcode = saveSelBrandList[j].brandCode;
                if(curbrandcode == savebrandcode) {
                    isExist = true;
                    break;
                }
            }
            if(!isExist) {
                var selBrandObj = {
                    "categoryCode": curCategoryCode,
                    "brandCode": curbrandcode
                };
                //如果全选品牌，列表中不存在的需要添加到保存列表中
                mainCtrl.selBrandList.push(selBrandObj);
            }
        }
    };
    //获取任务详情
    var getTaskInfo = function(taskId, pageType) {
        $.ajax({
            type: "post",
            dataType: "json",
            data: {
                "taskId": taskId
            },
            url: DI.queryModelTaskInfo,
            success: function(data) {
                var taskObj = data.data;
                mainCtrl.starttime = taskObj.startTime;
                mainCtrl.endtime = taskObj.endTime;
                mainCtrl.storageVal = taskObj.storage;
//                mainCtrl.taskType = taskObj.taskType;
                popCtrl.storeType = taskObj.storeType;
                mainCtrl.storeList = taskObj.storeCodeList;
                mainCtrl.selBrandList = [];

                if(pageType == 0) {
                    mainCtrl.allCategory = taskObj.cateBrandList;
                    //如果有品类，初始化话的时候获取第一条品类对应的品牌
                    if(mainCtrl.allCategory.length > 0) {
                        mainCtrl.allBrandByCate = mainCtrl.allCategory[0].brandList;
                        mainCtrl.curCategory = mainCtrl.allCategory[0];
                    }
                } else if(pageType == 1) {
                    //编辑的时候要展示选中的
                    var selbrandlist = [];
                    for(var i = 0; i < taskObj.cateBrandList.length; i++) {
                        var blist = taskObj.cateBrandList[i].brandList,
                            ccode = taskObj.cateBrandList[i].categoryCode;
                        for(var j = 0; j < blist.length; j++) {
                            var brandCode = blist[j].brandCode;
                            brandObj = {
                                "categoryCode": ccode,
                                "brandCode": brandCode
                            };
                            selbrandlist.push(brandObj);
                        }
                        //初始化的时候还要显示（已选）
                        for(var k = 0; k < mainCtrl.allCategory.length; k++) {
                            var allccode = mainCtrl.allCategory[k].categoryCode;
                            if(allccode == ccode) {
                                $("#sel_" + ccode).show();
                                break;
                            }
                        }
                    }
                    mainCtrl.selBrandList = selbrandlist;
                    checkSelBrand();
                }
            }
        });
    }

    //判断是否选中了所有的品类品牌
    var chkSelAllCategory = function() {
        var selBrandsLen = mainCtrl.selBrandList.length,
            allBrandsLen = mainCtrl.allCategoryBrand.length;
        //如果当前选中的品牌数量==整个数量 则代表选择了所有
        if(selBrandsLen == allBrandsLen) {
            mainCtrl.isSelAllCategory = true;
            $("#allcategory").prop("checked", true); //全选品类品牌
        } else {
            mainCtrl.isSelAllCategory = false;
            $("#allcategory").removeAttr("checked");
        }
    };
    //获取所有品类、品牌
    var getAllCategoryBrand = function() {
        $.ajax({
            type: "post",
            dataType: "json",
            url: DI.queryCategoryBrand,
            success: function(data) {

                mainCtrl.allCategory = data.data;
                //如果有品类，初始化话的时候获取第一条品类对应的品牌
                if(mainCtrl.allCategory.length > 0) {
                    mainCtrl.allBrandByCate = mainCtrl.allCategory[0].brandList;
                    mainCtrl.curCategory = mainCtrl.allCategory[0];
                }
                for(var i = 0; i < mainCtrl.allCategory.length; i++) {
                    var brands = mainCtrl.allCategory[i].brandList;
                    for(var j = 0; j < brands.length; j++) {
                        mainCtrl.allCategoryBrand.push({
                            "brandCode": brands[j].brandCode,
                            "brandName": brands[j].brandName
                        });
                    }
                }
            }
        });
    };

    //根据品类编码获取品牌
    var getBrandByCode = function(categoryCode) {
        var allCategoryList = mainCtrl.allCategory,
            allCategoryLen = allCategoryList.length;
        mainCtrl.allBrandByCate = [];
        for(var i = 0; i < allCategoryLen; i++) {
            if(allCategoryList[i].categoryCode == categoryCode) {
                mainCtrl.allBrandByCate = allCategoryList[i].brandList;
                break;
            }
        }
    };
    //检查在保存列表中有没有已经选中的品牌，如果有再次打开的时候需要显示选中状态
    var checkSelBrand = function() {
        var brands = mainCtrl.allBrandByCate,
            brandsLen = brands.length,
            selBrands = mainCtrl.selBrandList,
            selBrandsLen = selBrands.length,
            tempList = [];
        for(var i = 0; i < brandsLen; i++) {
            var bcode = brands[i].brandCode,
                bcodeObj = brands[i];
            bcodeObj.isSel = false;
            for(var j = 0; j < selBrandsLen; j++) {
                var sbcode = selBrands[j].brandCode;
                if(sbcode == bcode) {
                    bcodeObj.isSel = true;
                    break;
                }
            }
            tempList.push(bcodeObj);
        }
        if(tempList.length != 0) {
            mainCtrl.allBrandByCate = tempList;
        }

        setTimeout(function() {
            var selLen = $(".category-brand .brand li.sel").length;
            if(mainCtrl.allBrandByCate.length == selLen) {
                mainCtrl.isSelAllBrand = true;
                $("#allbrand").prop("checked", true);
            } else {
                mainCtrl.isSelAllBrand = false;
                $("#allbrand").removeAttr("checked");
            }
        }, 0);

    };
    //全部组织树门店 DI.queryOrgTree
    var getAllStore = function(storeType) {
        $(".loadTree").show();
        $.ajax({
            type: "post",
            dataType: "json",
            data: {
                "storeType": storeType
            },
            url: DI.queryOrgTree,
            success: function(data) {
                $(".loadTree").hide();
                var setting = {
                    view: {
                        expandSpeed: "",
                        fontCss: function(treeId, treeNode) {
                            return(!!treeNode.highlight) ? {
                                backgroundColor: "#FFFF00"
                            } : {
                                backgroundColor: ""
                            };
                        }
                    },
                    data: {
                        key: {
                            name: "text"
                        },
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "pid",
                            rootPId: 0
                        }
                    },
                    check: {
                        enable: true
                    }
                };
                data = data.data;
                if(mainCtrl.pageType == 0) {
                    var viewStoreList = mainCtrl.storeList,
                        viewStoreLen = viewStoreList.length,
                        newTreeData = [];
                    for(var i = 0; i < viewStoreLen; i++) {
                        var storeCode = viewStoreList[i];
                        for(var j = 0; j < data.length; j++) {
                            var tstorecode = data[j].id;
                            if(data[j].level == 3 && storeCode == tstorecode) {
                                newTreeData.push(data[j]);
                            }
                        }
                    }
                    data = newTreeData;
                    setting.check.enable = false;
                }
                var treeId = "storeTree";
                if(storeType == 0) {
                    treeId = "serviceTree";
                }
                var zNodes = mainCtrl.getNodes(data);
                $.fn.zTree.init($("#" + treeId), setting, zNodes);
                var tree = $.fn.zTree.getZTreeObj(treeId),
                    nodes = tree.transformToArray(tree.getNodes());
                tree.expandAll(true);

                if(storeType == 1) {
                    popCtrl.storeData = zNodes;
                } else {
                    popCtrl.serviceData = zNodes;
                }

                if(mainCtrl.pageType != 2) {
                    for(var i = 0; i < nodes.length; i++) {
                        if(nodes[i].level == 3) {
                            var isExist = false;
                            for(var j = 0; j < mainCtrl.storeList.length; j++) {
                                if(nodes[i].id == mainCtrl.storeList[j]) {
                                    isExist = true;
                                    tree.checkNode(nodes[i], true, true);
                                }
                            }
                        }
                    }
                }

            }
        });
    }

    var popCtrl = avalon.define({
        $id: "popController",
        tToggle: false,
        storeType: 1,
        keyword: "",
        search: function() {
            var treeId = "storeTree";
            if(popCtrl.storeType == 0) {
                treeId = "serviceTree"
            }
            var data = popCtrl.$model,
                tree = $.fn.zTree.getZTreeObj(treeId),
                nodeList = tree.getNodesByFilter(function(node, keyword) {
                    if(keyword != "") {
                        if(node.text && node.text.indexOf(keyword) != -1) {
                            return true;
                        }
                        if(node.id && node.id.indexOf(keyword) != -1 && node.level == 3) {
                            return true;
                        }
                    }
                }, false, false, $("#keywordId").val());
            //先初始化样式，不高亮
            var treeNodes = tree.transformToArray(tree.getNodes());
            for(var i = 0; i < treeNodes.length; i++) {
                treeNodes[i].highlight = false;
                tree.updateNode(treeNodes[i]);
            }
            if(nodeList && nodeList.length > 0) {
                tree.expandAll(false); //收起所有的
                for(var i = 0; i < nodeList.length; i++) {
                    var nodeObj = nodeList[i];
                    nodeObj.highlight = true;
                    tree.updateNode(nodeObj);
                    //展开指定的
                    if(nodeObj.isParent) {
                        tree.expandNode(nodeObj, true);
                    } else {
                        tree.expandNode(nodeObj.getParentNode(), true);
                    }
                }
            }
        },
        storeData: null,
        serviceData: null,
        callback: function() {
            //1门店 0服务站
            if(popCtrl.storeType == 1) {
                if(!popCtrl.storeData) {
                    getAllStore(1);
                }
            } else {
                if(!popCtrl.serviceData) {
                    getAllStore(0);
                }
            }
        },
        //保存当前选中的所有节点
        saveNodes: function() {
        	 //如果是查看，是不允许操作的
            if(mainCtrl.pageType == 0) {
            	 $("#popup_cnt").hide();
                return;
            }
            
            var treeId = "storeTree"
            if(popCtrl.storeType == 0) {
                treeId = "serviceTree";
            }
            var treeObj = $.fn.zTree.getZTreeObj(treeId),
                nodes = treeObj.getNodesByFilter(function(node) {
                    if(node.level == 3 && node.checked) return true;
                }, false);
            mainCtrl.storeList = [];
            if(nodes[0]) {
                var tree = $.fn.zTree.getZTreeObj(treeId);
                var nodes = tree.getCheckedNodes(true);
                for(var i = 0; i < nodes.length; i++) {
                    if(!nodes[i].isParent) {
                        mainCtrl.storeList.push(nodes[i].id);
                    }
                }
                $("#popup_cnt").hide();
            } else {
                $("#popup_cnt .dialog .err-box").show();
                setTimeout(function() {
                    $("#popup_cnt .dialog .err-box").hide();
                }, 2000);
            }

        },
        //取消要清空树的选择
        //      cancelSelNode: function() {
        //          mainCtrl.storeList = [];
        //          var treeObj = $.fn.zTree.getZTreeObj("storeTree");
        //          treeObj.checkAllNodes(false);
        //          $("#popup_cnt").hide();
        //      }
    });

    //获取URL数据
    var urlParams = PLATFORM.getUrlArgs();
    mainCtrl.pageType = urlParams.pageType;
    mainCtrl.taskId = urlParams.taskId;
    if(mainCtrl.pageType == 0) {
        popCtrl.tToggle = true; //查看时树同样不能编辑
        getTaskInfo(mainCtrl.taskId, mainCtrl.pageType);
    } else {
        //初始化获取所有品类品牌数据
        getAllCategoryBrand();
        if(mainCtrl.pageType == 1) {
            popCtrl.tToggle = true; //编辑时树同样不能编辑
            getTaskInfo(mainCtrl.taskId, mainCtrl.pageType);
        }
    }

    //实例化时间
    $("#starttime").datepicker({
        dateFormat: "yy-mm-dd",
        minDate: getMinDate(0),
        onClose: function(selectedDate) {
            $("#endtime").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#endtime").datepicker({
        dateFormat: "yy-mm-dd",
        onClose: function(selectedDate) {
            $("#starttime").datepicker("option", "maxDate", selectedDate);
        }
    });

    avalon.scan();
});